import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => {
    // console.log(err);
    // console.warn(err);
    // console.error(err);
  });
};
Vue.use(VueRouter);

const routes = [
  // 路由重定向
  // / => /home
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
  },
  {
    path: '/search_cinema',
    name: 'search_cinema',
    component: () => import('@/views/SearchCinema.vue'),
  },
  {
    path: '/cinema_detail',
    name: 'cinema_detail',
    component: () => import('@/views/CinemaDetail.vue'),
  },
  {
    path: '/movie',
    name: 'movie',
    component: () => import('@/views/MovieView.vue'),
  },
  {
    path: '/cinema',
    name: 'cinema',
    component: () => import('@/views/CinemaView.vue'),
  },
  {
    path: '/my',
    name: 'my',
    component: () => import('@/views/MyView.vue'),
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue'),
  },
  {
    path: '/my_order',
    name: 'my_order',
    component: () => import('@/views/MyOrder.vue'),
  },
  {
    path: '/search_all',
    name: 'search_all',
    component: () => import('@/views/SearchView.vue'),
  },
  {
    path: '/search_movie',
    name: 'search_movie',
    component: () => import('@/views/SearchView.vue'),
  },
  {
    path: '/movie_detail',
    name: 'movie_detail',
    component: () => import('@/views/MovieDetail.vue'),
  },
  {
    path: '/select_cinema',
    name: 'select_cinema',
    component: () => import('@/components/SelectCinema.vue'),
  },
  {
    path: '/404',
    component: () => import('@/views/PageNotFound.vue'),
  },
  {
    path: '*',
    redirect: '/404',
  },
];

const router = new VueRouter({
  routes,
});
// 配置全局的前置的导航守卫
router.beforeEach((to, from, next) => {
  console.log('to:', to);
  console.log('from:', from);
  // 都需要登录之后才能访问
  let isLogin = false; // 目前没有登录
  let blackList = ['/my_order'];
  let needLogin = false;
  for (let i = 0; i < blackList.length; i++) {
    if (blackList[i] == to.path) {
      // 当前的路径需要权限控制的
      needLogin = true;
      break;
    }
  }
  // console.log(needLogin);
  if (needLogin) {
    if (isLogin) {
      next();
    } else {
      next({ path: 'login' });
    }
  } else {
    next();
  }
});

export default router;
